package com.hqyj.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Autor 伍军
 * @Date 2022/10/18 10:16
 * @Version 1.0
 **/
@Component
@ServerEndpoint(value = "/emWs")
public class EmailWebSocket {

    //创建一个集合记录会话ID
    private static List<Session> list = new LinkedList<>();

    @OnOpen
    public void open(Session session) throws IOException {
        System.out.println(session.getId()+"已经上线");
        //记录这个会话
        list.add(session);
        //发送sesionID给客户端
        Map<String,Object> map = new HashMap<>();
        map.put("id",session.getId());
        map.put("msg","");
        //把map转换成字符串
        ObjectMapper mapper = new ObjectMapper();
        String info = mapper.writeValueAsString(map);
        //发送消息给前端
        session.getBasicRemote().sendText(info);

    }

    @OnClose
    public void close(Session session){
        //去除关闭的客户端
        list.remove(session);
    }


    /**
     * 发送消息给前端的
     * @param id 当前客户单的ID
     * @param msg 推送的消息
     */
    public static void sendMsg(String id,String msg) throws IOException {
        for(Session s:list){
            if(s.getId().equals(id)){
                //判断客户端是否在线
                if(s.isOpen()){
                    Map<String,Object> map = new HashMap<>();
                    map.put("id",id);
                    map.put("msg",msg);

                    //把map转换成字符串
                    ObjectMapper mapper = new ObjectMapper();
                    String info = mapper.writeValueAsString(map);
                    //发送消息
                    s.getBasicRemote().sendText(info);
                }

            }
        }


    }

}
